<template>
  <div class="tinymce-editor">
    <editor
      v-model="stateValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick">
    </editor>
  </div>
</template>

<script>

  // 富文本
  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/plugins/advlist'
  import 'tinymce/plugins/anchor'
  import 'tinymce/plugins/autolink'
  import 'tinymce/plugins/autosave'
  import 'tinymce/plugins/bbcode'
  import 'tinymce/plugins/charmap'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/codesample'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/directionality'
  import 'tinymce/plugins/fullpage'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/plugins/help'
  import 'tinymce/plugins/hr'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/imagetools'
  import 'tinymce/plugins/importcss'
  import 'tinymce/plugins/insertdatetime'
  import 'tinymce/plugins/legacyoutput'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/nonbreaking'
  import 'tinymce/plugins/noneditable'
  import 'tinymce/plugins/pagebreak'
  import 'tinymce/plugins/paste'
  import 'tinymce/plugins/preview'
  import 'tinymce/plugins/print'
  import 'tinymce/plugins/quickbars'

  import 'tinymce/plugins/save'
  import 'tinymce/plugins/searchreplace'
  import 'tinymce/plugins/spellchecker'
  import 'tinymce/plugins/tabfocus'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/template'
  import 'tinymce/plugins/textcolor'
  import 'tinymce/plugins/textpattern'
  import 'tinymce/plugins/toc';
  import 'tinymce/plugins/visualblocks';
  import 'tinymce/plugins/visualchars';
  import 'tinymce/plugins/wordcount';
  import 'tinymce/icons/default';
  import {appPublicPath, appApiBaseUrl} from '../../config/constant.config';
  import {concatUrl} from '../../utils/util'
  import { postAction, uploadFile } from '../../api/manage'
  import { fileManager } from '../../api/url'
  export default {
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        required:false
      },
      triggerChange:{
        type: Boolean,
        default: true,
        required:false
      },
      disabled: {
        type: Boolean,
        default: false
      },
      plugins: {
        type: [String, Array],
        default: 'print preview paste importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap quickbars',
      },
      toolbar: {
        type: [String, Array],
        default: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap  | fullscreen  preview save print | insertfile image media template link anchor codesample | ltr rtl',
      }
    },





  data() {
      return {
        //初始化配置
        init: {
          image_caption: true,
          quickbars_selection_toolbar: 'bold italic | quicklink h2 h3 blockquote quickimage quicktable',
          noneditable_noneditable_class: 'mceNonEditable',
          toolbar_mode: 'sliding',
          contextmenu: 'link image imagetools table',
          content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
          language_url: concatUrl(appPublicPath,'tinymce/langs/zh_CN.js'),
          language: 'zh_CN',
          skin_url: concatUrl(appPublicPath,'tinymce/skins/lightgray'),
          height: 300,
          plugins: this.plugins,
          toolbar: this.toolbar,
          branding: false,
          menubar: 'file edit view insert format tools table tc help',
          images_upload_handler: (blobInfo, success, failure, progress) => {
            let formData = new FormData();
            formData.append("type", 'tiny');
            formData.append("file", blobInfo.blob(), blobInfo.filename());

            uploadFile(fileManager.uploadUrl, formData, (e)=>  progress(e.loaded / e.total * 100))
              .then(res=>{
                if(res.success){
                  let result = concatUrl(concatUrl(appApiBaseUrl, fileManager.fileBaseUrl),res.result[0]);
                  if(!result.toLowerCase().startsWith("http")){
                    result = concatUrl(window.location.protocol+"//"+window.location.hostname, result)
                  }
                  success(result);
                }else {
                  try {
                    failure("上传失败");
                  } catch (e) {
                    console.error(e);
                  }
                }
              })
            // postAction(fileManager.uploadUrl, {file:blobInfo.base64(), type:'tiny'}).then(res=>{
            //
            //
            // })

          },
             // let img = new Image();
             //  let srcBase64 = blobInfo.base64();
             //  if(srcBase64.length<1000000){
             //    success("data:image/jpeg;base64,"+srcBase64);
             //    return;
             //  }
             //    img.src = "data:image/jpeg;base64," + blobInfo.base64();
             //  img.onload = () => {
             //    let width = img.width;
             //    let height = img.height;
             //    let ratio = 1000000/srcBase64.length;
             //    if(ratio<0.01){
             //      ratio = 0.01;
             //    }
             //    let canvas = document.createElement("canvas");
             //    canvas.width = width*ratio;
             //    canvas.height = height*ratio;
             //    let context = canvas.getContext("2d");
             //    context.drawImage(img, 0, 0,width*ratio, height*ratio);
             //    this.img = canvas.toDataURL("image/jpeg", 1);
             //    success(this.img);
             //  };
          // }
        },
        stateValue: this.value
      }
    },
    mounted() {
      tinymce.init({})
    },
    methods: {

      onClick(e) {
        this.$emit('onClick', e, tinymce)
      },
      //可以添加一些自己的自定义事件，如清空内容
      clear() {
        this.myValue = ''
      }
    },
    watch: {
      value(newValue) {

        if(!newValue){
          newValue = '';
        }
        this.stateValue = newValue
      },
      stateValue(newValue) {
        if(this.triggerChange){
          this.$emit('change', newValue)
        }else{
          this.$emit('input', newValue)
        }
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }

</script>
<style scoped>
</style>